package com.ayz.gateway.core.core.Netty;

import cn.hutool.log.Log;

import com.ayz.gateway.core.authorization.IAuth;
import com.ayz.gateway.core.context.config.Configuration;
import com.ayz.gateway.core.core.handlers.AuthorizationHandler;
import com.ayz.gateway.core.core.handlers.GatewayServerHandler;
import com.ayz.gateway.core.core.handlers.RequestParserHandler;
import com.ayz.gateway.core.session.GatewaySessionFactory;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import lombok.Data;

/**
 * @ClassName SessionChannelInitializer
 * @Description TODO: 接收Http协议，使用Netty做协议转换
 * @Date 2023/5/5 17:13
 * @Version 1.0
 **/
@Data
public class GatewayChannelInitializer extends ChannelInitializer<NioSocketChannel> {
    private final Log log=Log.get(GatewayChannelInitializer.class);
    /**
     * 处理工作的线程池
     */
    private final DefaultEventExecutorGroup workerGroup;
    /**
     * Netty Server端的配置参数
     */
    private final NettyServerConfig serverConfig;
    /**
     * 网关上下文的配置参数
     */
    private final Configuration configuration;
    /**
     * 网关上下文单例的 会话工厂
     */
    private final GatewaySessionFactory gatewaySessionFactory;
    /**
     * 网关网络层的鉴权模块的服务类
     */
    private IAuth authService;


    public GatewayChannelInitializer(NettyGatewayServer gatewayServer) {
        this.workerGroup=gatewayServer.getDefaultEventExecutorGroup();
        this.serverConfig=gatewayServer.getServerConfig();
        this.configuration =gatewayServer.getConfiguration();
        this.gatewaySessionFactory=gatewayServer.getGatewaySessionFactory();
        this.authService=gatewayServer.getAuthService();
    }

    @Override
    protected void initChannel(NioSocketChannel socketChannel) throws Exception {
        log.info("接收了来自客户端的连接:{"+socketChannel.remoteAddress()+"}");
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(
                workerGroup,
                new HttpRequestDecoder(),
                new HttpResponseEncoder(),
                new HttpObjectAggregator(1024*1024),
                new IdleStateHandler(0,0,serverConfig.getServerChannelMaxIdleTimeSeconds()),
                new RequestParserHandler(),
                new AuthorizationHandler(getAuthService(),getConfiguration()),
                new GatewayServerHandler(configuration,gatewaySessionFactory)
        );
    }
}
